package com.security.control.core.social.qq.api;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

/**
 * @author imoot@gamil.com
 * @date 2019/1/3 0003 15:04
 * -----qq相关操作实现类
 */
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {
    private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=YOUR_ACCESS_TOKEN";
    private static final String URL_GET_USER_INFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=YOUR_APP_ID&openid=YOUR_OPENID";

    private Logger log = LoggerFactory.getLogger(QQImpl.class);

    private String appId;
    private String openId;

    private ObjectMapper objectMapper = new ObjectMapper();

    public QQImpl(String accessToken, String appId) {
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);//传入accessToken和token的设置机制，告诉父类把accessToken作为请求参数来构造
        this.appId = appId;
        String url = StringUtils.replace(URL_GET_OPENID, "YOUR_ACCESS_TOKEN", accessToken);
        String result = getRestTemplate().getForObject(url, String.class);
        result = StringUtils.substring(result, StringUtils.indexOf(result, "(") + 1, StringUtils.lastIndexOf(result, ")"));//截取出有效字符串
        log.info("获取openid：" + result);
        this.openId = JSON.parseObject(result).getString("openid");//从返回的参数中取出openId
    }

    @Override
    public QQUserInfo getUserInfo() {
        String url = StringUtils.replace(URL_GET_USER_INFO, "YOUR_APP_ID", appId).replace("YOUR_OPENID", openId);
        String result = getRestTemplate().getForObject(url, String.class);//使用SpringSocial提供的rest请求模版根据url获取用户信息
        log.info("获取用户信息：" + result);
        try {
            QQUserInfo userInfo = objectMapper.readValue(result, QQUserInfo.class);//把请求后获得的用户信息用ObjectMapper绑定到实体类上
            userInfo.setOpenId(this.openId);//设置用户的openId
            return userInfo;
        } catch (Exception e) {
            log.error("获取QQ用户信息出现错误：", e);
            throw new RuntimeException("获取QQ用户信息出现错误：" + e);
        }
    }
}
